<script setup lang="ts">
import { ref, reactive, watch } from 'vue'
import { useRouter } from 'vue-router'
import { useCurrentUserStore } from '@/stores/useCurrentUserStore.ts' // 确保路径正确
import { ElMessage, ElMessageBox, type UploadProps } from 'element-plus' // 引入Element Plus组件，用于更好的用户提示
import type { User } from '@/utils/dataType/UserModel'
import { formatDate } from '@/utils/commonMessage/common.ts'
import { updateUserInfor } from '@/services/api/user.ts'
import { defaults } from 'axios' // 确保类型定义路径正确

const currentUserStore = useCurrentUserStore()
// const router = useRouter()

// --- 个人信息展示与编辑 ---
const isEditingInfo = ref(false)
// 使用 reactive 声明响应式对象，直接绑定到 Store 的数据，以便双向绑定
// 注意：直接修改 store 的 state 是可以的，但在实际应用中，通常会通过 action 或 mutation 来修改
// 这里为了简化编辑逻辑，直接复制一份进行编辑，保存时再提交给 store
const editableUserInfo = reactive<User>({ ...currentUserStore.loginUser.infor }) //新提交的编辑的用户信息

watch(
  () => currentUserStore.loginUser.infor,
  (newVal) => {
    // 当 Pinia store 中的用户信息更新时，同步到 editableUserInfo
    Object.assign(editableUserInfo, newVal) //当用户信息改变时，同步到要编辑的信息
  },
  { deep: true, immediate: true }, // 深度监听并立即执行一次
)
//开始编辑
const startEditing = () => {
  // 复制当前用户信息到编辑副本
  Object.assign(editableUserInfo, currentUserStore.loginUser.infor)
  isEditingInfo.value = true
}
//保存用户信息
const saveUserInfo = async () => {
  // 这里应该进行数据校验和实际的 API 调用来更新用户信息
  // 假设有一个更新用户信息的 action
  try {
    editableUserInfo.birthday = formatDate(editableUserInfo.birthday)
    const res = await updateUserInfor(editableUserInfo)
    currentUserStore.loginUser.infor = { ...editableUserInfo }
    localStorage.setItem('user', JSON.stringify(currentUserStore.loginUser))
    // if (res.status == 200 && res.data.code == 1) {
    //   currentUserStore.loginUser.infor = { ...editableUserInfo }
    // } else {
    //   ElMessage.error('出错了:' + res.data.msg)
    // }
    isEditingInfo.value = false
    ElMessage.success('个人信息已保存！')
  } catch (error) {
    ElMessage.error('保存失败，请重试:', error)
    console.error('保存用户信息失败:', error)
  }
}

const cancelEditing = () => {
  isEditingInfo.value = false
  // 恢复 editableUserInfo 到原始状态
  Object.assign(editableUserInfo, currentUserStore.loginUser.infor)
}

// // --- 头像修改 ---
// const avatarInputRef = ref<HTMLInputElement | null>(null)
//
// const openAvatarUpload = () => {
//   avatarInputRef.value?.click()
// }
//
// const handleAvatarChange = async (event: Event) => {
//   const file = (event.target as HTMLInputElement).files?.[0]
//   if (file) {
//     if (!file.type.startsWith('image/')) {
//       ElMessage.error('请上传图片格式的文件！')
//       return
//     }
//     if (file.size > 2 * 1024 * 1024) {
//       ElMessage.error('头像文件大小不能超过 2MB！')
//       return
//     }
//
//     const reader = new FileReader()
//     reader.onload = async (e) => {
//       // 预览新头像
//       const newAvatarUrl = e.target?.result as string
//
//       // 弹窗确认
//       ElMessageBox.confirm('确定要更换头像吗？', '提示', {
//         confirmButtonText: '确定',
//         cancelButtonText: '取消',
//         type: 'warning'
//       })
//         .then(async () => {
//           // 这里应该将文件上传到服务器，并更新 store 中的 avatarUrl
//           //todo
//           // 模拟上传成功后更新 store
//           // await currentUserStore.updateAvatar(newAvatarUrl); // 假设 store 有此 action
//           currentUserStore.updateAvatar(file)
//           currentUserStore.loginUser.infor.avatarUrl = newAvatarUrl // 模拟更新
//           ElMessage.success('头像更新成功！')
//         })
//         .catch(() => {
//           ElMessage.info('已取消头像更换。')
//         })
//     }
//     reader.readAsDataURL(file)
//   }
// }

//todo修改头像
const avatarUpload: UploadProps['httpRequest'] = async (options) => {
  try {
    console.log('上传图片')
    const formData = new FormData()
    formData.append('file', options.file)
    const res = await currentUserStore.updateAvatar(formData)
  } catch (error) {
    console.error('用户头像上传失败:', error)
  }
}

// --- 我的活动 (收藏, 点赞, 评论) ---
const currentActivityTab = ref('favorites') // 默认显示收藏

// 模拟数据，实际项目中应从后端获取
const userActivities = reactive({
  favorites: [],
  likes: [],
  comments: [],
})
// --- 推荐景点 ---
const recommendedSpots = reactive([])
import defaultImage from '@/assets/loading.png'

const setDefaultImage = (e) => {
  e.target.src = defaultImage
}
</script>

<template>
  <div class="user-profile-container">
    <header class="profile-header">
      <h1>个人中心</h1>
    </header>

    <section class="user-info-section">
      <div class="avatar-wrapper">
        <img
          :src="currentUserStore.loginUser.infor.avatar || 'https://via.placeholder.com/150'"
          @error="setDefaultImage"
          alt="用户头像"
          class="user-avatar"
          @click="openAvatarUpload"
        />
        <el-upload
          class="upload-demo"
          :http-request="avatarUpload"
          :multiple="false"
          :auto-upload="true"
          :show-file-list="false"
          :on-preview="handlePreview"
          :on-remove="handleRemove"
          :before-remove="beforeRemove"
          :limit="1"
          :on-exceed="handleExceed"
        >
          <el-button type="primary">修改头像</el-button>
        </el-upload>
        <!--        <input-->
        <!--          type="file"-->
        <!--          ref="avatarInputRef"-->
        <!--          style="display: none"-->
        <!--          @change="handleAvatarChange"-->
        <!--          accept="image/*"-->
        <!--        />-->
        <!--        <button class="edit-avatar-btn" @click="openAvatarUpload">修改头像</button>-->
        <el-button type="primary" @click="currentUserStore.userLogout()" style="margin-top: 20px">
          退出登录
        </el-button>
      </div>

      <div class="info-details">
        <div class="info-item">
          <label for="nickname">昵称:</label>
          <span v-if="!isEditingInfo">{{
            currentUserStore.loginUser.infor.username || '未设置'
          }}</span>
          <input v-else type="text" id="nickname" v-model="editableUserInfo.username" />
        </div>

        <div class="info-item">
          <label for="nickname">密码:</label>
          <span v-if="!isEditingInfo">{{
            currentUserStore.loginUser.infor.password || '未设置'
          }}</span>
          <input v-else type="text" id="password" v-model="editableUserInfo.password" />
        </div>

        <div class="info-item">
          <label for="nickname">姓名:</label>
          <span v-if="!isEditingInfo">{{ currentUserStore.loginUser.infor.name || '未设置' }}</span>
          <input v-else type="text" id="nickname" v-model="editableUserInfo.name" />
        </div>
        <div class="info-item">
          <label for="gender">性别:</label>
          <span v-if="!isEditingInfo">{{ currentUserStore.loginUser.infor.sex || '保密' }}</span>
          <select v-else id="gender" v-model="editableUserInfo.sex">
            <option value="男">男</option>
            <option value="女">女</option>
            <option value="保密">保密</option>
          </select>
        </div>
        <div class="info-item">
          <label for="email">电子邮箱:</label>
          <span v-if="!isEditingInfo">{{
            currentUserStore.loginUser.infor.email || '未设置'
          }}</span>
          <input v-else type="text" id="email" v-model="editableUserInfo.email" />
        </div>
        <div class="info-item">
          <label for="phone">电话:</label>
          <span v-if="!isEditingInfo">{{
            currentUserStore.loginUser.infor.phone || '未设置'
          }}</span>
          <input v-else type="text" id="phone" v-model="editableUserInfo.phone" />
        </div>

        <div class="info-item">
          <label for="phone">生日:</label>
          <span v-if="!isEditingInfo">{{
            currentUserStore.loginUser.infor.birthday || '未设置'
          }}</span>
          <el-date-picker
            v-else
            id="birthday"
            v-model="editableUserInfo.birthday"
            type="date"
            placeholder="Pick a day"
            :size="size"
          />
          <!--          <input v-else type="text" id="phone" v-model="editableUserInfo.birthday" />-->
        </div>

        <div class="info-actions">
          <div v-if="!isEditingInfo">
            <el-button @click="startEditing" type="primary">编辑资料</el-button>
          </div>
          <div v-else>
            <button @click="saveUserInfo">保存</button>
            <button class="cancel-btn" @click="cancelEditing">取消</button>
          </div>
        </div>
      </div>
    </section>

    <section class="user-activities-section">
      <h2>我的活动</h2>
      <div class="activity-tabs">
        <button
          :class="{ active: currentActivityTab === 'favorites' }"
          @click="currentActivityTab = 'favorites'"
        >
          我的收藏
        </button>
        <button
          :class="{ active: currentActivityTab === 'likes' }"
          @click="currentActivityTab = 'likes'"
        >
          我的点赞
        </button>
        <button
          :class="{ active: currentActivityTab === 'comments' }"
          @click="currentActivityTab = 'comments'"
        >
          我的评论
        </button>
      </div>

      <div class="activity-content">
        <div v-if="currentActivityTab === 'favorites'" class="activity-list">
          <div v-if="userActivities.favorites.length === 0" class="empty-state">
            <p>还没有收藏任何内容哦。</p>
          </div>
          <div v-else class="activity-item" v-for="item in userActivities.favorites" :key="item.id">
            <h3>{{ item.title }}</h3>
            <p>{{ item.description }}</p>
            <router-link :to="item.targetUrl">查看详情</router-link>
          </div>
        </div>

        <div v-if="currentActivityTab === 'likes'" class="activity-list">
          <div v-if="userActivities.likes.length === 0" class="empty-state">
            <p>还没有点赞任何内容哦。</p>
          </div>
          <div v-else class="activity-item" v-for="item in userActivities.likes" :key="item.id">
            <h3>{{ item.title }}</h3>
            <p>{{ item.description }}</p>
            <router-link :to="item.targetUrl">查看详情</router-link>
          </div>
        </div>

        <div v-if="currentActivityTab === 'comments'" class="activity-list">
          <div v-if="userActivities.comments.length === 0" class="empty-state">
            <p>还没有发表评论哦。</p>
          </div>
          <div v-else class="activity-item" v-for="item in userActivities.comments" :key="item.id">
            <h3>评论于：{{ item.targetTitle }}</h3>
            <p>"{{ item.content }}"</p>
            <router-link :to="item.targetUrl">查看原文</router-link>
          </div>
        </div>
      </div>
    </section>

    <section class="recommended-spots-section">
      <h2>推荐景点</h2>
      <div v-if="recommendedSpots.length === 0" class="empty-state">
        <p>暂时没有推荐的景点。</p>
      </div>
      <div v-else class="spot-grid">
        <div class="spot-card" v-for="spot in recommendedSpots" :key="spot.id">
          <img :src="spot.imageUrl" :alt="spot.name" class="spot-image" />
          <div class="spot-info">
            <h3>{{ spot.name }}</h3>
            <p>{{ spot.description }}</p>
            <router-link :to="spot.spotUrl">查看详情</router-link>
          </div>
        </div>
      </div>
    </section>
  </div>
</template>

<style scoped>
/* 整体容器 */
.user-profile-container {
  max-width: 960px;
  margin: 40px auto;
  padding: 30px;
  background-color: #ffffff;
  border-radius: 12px;
  box-shadow: 0 6px 20px rgba(0, 0, 0, 0.08);
  font-family:
    'Segoe UI', 'Roboto', 'Oxygen', 'Ubuntu', 'Cantarell', 'Fira Sans', 'Droid Sans',
    'Helvetica Neue', sans-serif;
  color: #333;
}

/* 头部样式 */
.profile-header {
  text-align: center;
  margin-bottom: 40px;
  padding-bottom: 20px;
  border-bottom: 1px solid #eee;
}

.profile-header h1 {
  font-size: 2.8em;
  color: #2c3e50;
  font-weight: 700;
  letter-spacing: 1px;
}

/* 个人信息部分 */
.user-info-section {
  display: flex;
  align-items: center;
  gap: 60px;
  margin-bottom: 50px;
  background-color: #f9f9f9;
  padding: 30px;
  border-radius: 10px;
  box-shadow: inset 0 2px 5px rgba(0, 0, 0, 0.03);
}

.avatar-wrapper {
  position: relative;
  width: 180px;
  height: 180px;
  flex-shrink: 0;
}

.user-avatar {
  width: 100%;
  height: 100%;
  border-radius: 50%;
  object-fit: cover;
  border: 4px solid #fff;
  box-shadow: 0 0 0 5px rgba(0, 123, 255, 0.2);
  transition: transform 0.3s ease-in-out;
  cursor: pointer;
}

.user-avatar:hover {
  transform: scale(1.05);
}

.edit-avatar-btn {
  position: absolute;
  bottom: 10px;
  right: 10px;
  background-color: rgba(0, 0, 0, 0.6);
  color: #fff;
  border: none;
  border-radius: 20px;
  padding: 8px 15px;
  font-size: 0.9em;
  cursor: pointer;
  opacity: 0.9;
  transition: opacity 0.3s ease-in-out;
}

.edit-avatar-btn:hover {
  opacity: 1;
  background-color: #007bff;
}

.info-details {
  flex-grow: 1;
}

.info-item {
  display: flex;
  align-items: center;
  margin-bottom: 18px;
  font-size: 1.1em;
}

.info-item label {
  font-weight: bold;
  color: #555;
  width: 90px; /* 统一标签宽度 */
  flex-shrink: 0;
}

.info-item span,
.info-item input,
.info-item select,
.info-item textarea {
  flex-grow: 1;
  padding: 10px 15px;
  border: 1px solid #ddd;
  border-radius: 6px;
  font-size: 1em;
  transition: border-color 0.3s;
}

.info-item input:focus,
.info-item select:focus,
.info-item textarea:focus {
  border-color: #007bff;
  outline: none;
  box-shadow: 0 0 0 3px rgba(0, 123, 255, 0.15);
}

.info-item textarea {
  min-height: 80px;
  resize: vertical;
}

.info-actions {
  text-align: right;
  margin-top: 25px;
}

.info-actions button {
  background-color: #007bff;
  color: white;
  border: none;
  padding: 12px 25px;
  border-radius: 8px;
  cursor: pointer;
  font-size: 1.05em;
  margin-left: 15px;
  transition:
    background-color 0.3s ease,
    transform 0.2s ease;
  box-shadow: 0 4px 10px rgba(0, 123, 255, 0.2);
}

.info-actions button:hover {
  background-color: #0056b3;
  transform: translateY(-2px);
}

.info-actions button:active {
  transform: translateY(0);
}

.info-actions .cancel-btn {
  background-color: #6c757d;
}

.info-actions .cancel-btn:hover {
  background-color: #5a6268;
}

/* 我的活动部分 */
.user-activities-section,
.recommended-spots-section {
  margin-bottom: 50px;
  padding: 30px;
  background-color: #f9f9f9;
  border-radius: 10px;
  box-shadow: inset 0 2px 5px rgba(0, 0, 0, 0.03);
}

h2 {
  font-size: 2em;
  color: #2c3e50;
  margin-bottom: 25px;
  border-bottom: 2px solid #007bff;
  padding-bottom: 10px;
  display: inline-block;
  letter-spacing: 0.5px;
}

.activity-tabs {
  display: flex;
  gap: 15px;
  margin-bottom: 25px;
  border-bottom: 1px solid #eee;
  padding-bottom: 10px;
}

.activity-tabs button {
  background-color: #e9ecef;
  color: #495057;
  border: none;
  padding: 10px 20px;
  border-radius: 6px 6px 0 0;
  cursor: pointer;
  font-size: 1em;
  transition:
    background-color 0.3s,
    color 0.3s;
}

.activity-tabs button:hover {
  background-color: #dee2e6;
}

.activity-tabs button.active {
  background-color: #007bff;
  color: white;
  font-weight: bold;
  border-bottom: 3px solid #0056b3;
}

.activity-list {
  display: grid;
  gap: 20px;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
}

.activity-item {
  background-color: #fff;
  border: 1px solid #e0e0e0;
  border-radius: 8px;
  padding: 20px;
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.05);
  transition:
    transform 0.3s ease,
    box-shadow 0.3s ease;
}

.activity-item:hover {
  transform: translateY(-5px);
  box-shadow: 0 8px 20px rgba(0, 0, 0, 0.1);
}

.activity-item h3 {
  font-size: 1.3em;
  color: #34495e;
  margin-bottom: 10px;
}

.activity-item p {
  font-size: 0.95em;
  color: #666;
  line-height: 1.6;
  margin-bottom: 15px;
}

.activity-item router-link {
  color: #007bff;
  text-decoration: none;
  font-weight: 500;
  transition: color 0.3s;
}

.activity-item router-link:hover {
  color: #0056b3;
  text-decoration: underline;
}

/* 推荐景点部分 */
.spot-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
  gap: 30px;
}

.spot-card {
  background-color: #fff;
  border-radius: 10px;
  overflow: hidden;
  box-shadow: 0 6px 18px rgba(0, 0, 0, 0.08);
  transition:
    transform 0.3s ease,
    box-shadow 0.3s ease;
}

.spot-card:hover {
  transform: translateY(-8px);
  box-shadow: 0 10px 25px rgba(0, 0, 0, 0.15);
}

.spot-image {
  width: 100%;
  height: 200px;
  object-fit: cover;
  border-bottom: 1px solid #eee;
}

.spot-info {
  padding: 20px;
}

.spot-info h3 {
  font-size: 1.4em;
  color: #2c3e50;
  margin-bottom: 10px;
}

.spot-info p {
  font-size: 0.9em;
  color: #666;
  line-height: 1.5;
  margin-bottom: 15px;
  display: -webkit-box;
  -webkit-line-clamp: 3; /* 限制三行文字 */
  -webkit-box-orient: vertical;
  overflow: hidden;
  text-overflow: ellipsis;
}

.spot-info router-link {
  display: inline-block;
  background-color: #007bff;
  color: white;
  padding: 10px 20px;
  border-radius: 6px;
  text-decoration: none;
  font-size: 0.95em;
  transition: background-color 0.3s ease;
}

.spot-info router-link:hover {
  background-color: #0056b3;
}

/* 空状态提示 */
.empty-state {
  text-align: center;
  padding: 40px 20px;
  background-color: #f0f8ff;
  border: 1px dashed #b3e0ff;
  border-radius: 8px;
  color: #6a8ead;
  font-size: 1.1em;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .user-profile-container {
    padding: 20px;
    margin: 20px auto;
  }

  .user-info-section {
    flex-direction: column;
    text-align: center;
    gap: 30px;
  }

  .avatar-wrapper {
    width: 150px;
    height: 150px;
  }

  .info-item {
    flex-direction: column;
    align-items: flex-start;
  }

  .info-item label {
    margin-bottom: 5px;
    width: auto;
  }

  .info-actions {
    display: flex;
    justify-content: center;
    gap: 10px;
    margin-top: 20px;
  }

  .info-actions button {
    margin-left: 0;
  }

  .activity-tabs {
    flex-wrap: wrap;
    justify-content: center;
  }

  .activity-tabs button {
    margin-bottom: 10px;
  }

  .spot-grid {
    grid-template-columns: 1fr; /* 小屏幕下改为单列 */
  }
}
</style>
